package cn.zzuli.loginandregister;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class RegisterActivity extends AppCompatActivity {
    private Button confirm_btn;
    String registerUrl = "https://www.wanandroid.com/user/register";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_register );

        EditText etName = findViewById ( R.id.username );
        EditText etPwd = findViewById ( R.id.userpwd );
        EditText conPwd = findViewById ( R.id.confirm_pwd);
        confirm_btn = (Button) findViewById(R.id.confirm_btn);
        confirm_btn.setOnClickListener (new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String name = etName.getText().toString ();
                String pwd = etPwd.getText().toString ();
                String con_pwd = conPwd.getText().toString ();
                new Thread(){
                    @Override
                    public void run(){
                        String data2 = REGISTER ( name,pwd,con_pwd );
                        //System.out.println (data2);
                        try {
                            JSONObject object2 = new JSONObject (data2);
                            int error = object2.optInt ( "errorCode" );
                            String errorMsg = object2.optString ( "errorMsg" );
                            System.out.println (error+"  "+errorMsg);
                            if(error == 0){
                                //注册成功
                                runOnUiThread ( new Runnable () {
                                    @Override
                                    public void run() {
                                        Toast.makeText ( RegisterActivity.this,"注册成功",
                                                Toast.LENGTH_SHORT ).show ();
                                        Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
                                        startActivity(intent);
                                    }
                                } );

                            }else{
                                //注册失败
                                runOnUiThread ( new Runnable () {
                                    @Override
                                    public void run() {
                                        Toast.makeText ( RegisterActivity.this,errorMsg,
                                                Toast.LENGTH_SHORT ).show ();
                                    }
                                } );
                            }
                        } catch (JSONException e) {
                            e.printStackTrace ();
                        }
                    }
                }.start();
            }
        } );
    }
    private String REGISTER(String name, String pwd, String con_pwd) {
        try {
            URL url = new URL(registerUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //conn.setReadTimeout(5000);
            //conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            //conn.setDoInput(true);
            conn.setUseCaches(false);
            String str = "username=" + URLEncoder.encode(name, "utf-8")
                    + "&password=" + URLEncoder.encode(pwd, "utf-8")
                    + "&repassword=" + URLEncoder.encode(con_pwd, "utf-8");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(str.getBytes());
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                String s = stream2String ( inputStream );
                //System.out.println(s);
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String stream2String(InputStream is){
        BufferedReader br=new BufferedReader(new InputStreamReader (is));
        StringBuffer buffer=new StringBuffer();
        String line=null;
        try{
            while ((line=br.readLine()) != null){
                buffer.append(line);
            }
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace ();
        }
        return null;
    }
}